//
//  ImageViewController.m
//  PichImageView
//
//  Created by APPLE on 17/1/16.
//  Copyright © 2017年 Gibson. All rights reserved.
//

#import "ImageViewController.h"

@interface ImageViewController () <UIGestureRecognizerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (strong, nonatomic) UIImagePickerController *pickerVC;
@property (strong, nonatomic) UIImageView *imageView;
@property (assign, nonatomic) CGRect originalFrame;
@property (assign, nonatomic) CGFloat lastScale;
@end

@implementation ImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavigationBar];
    [self initSubViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)initNavigationBar {
    UIBarButtonItem *addItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAdd target: self action: @selector(addImage:)];
    self.navigationItem.rightBarButtonItem = addItem;
    
    self.title = @"选择图片";
}

-(void)addImage:(UIBarButtonItem *) item {
    [self presentViewController: self.pickerVC animated: YES completion: nil];
}


-(void)initSubViews {
    self.view.backgroundColor = [UIColor yellowColor];
    [self.view addSubview: self.imageView];
    __weak typeof(self) weakSelf = self;
//    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.top.right.mas_equalTo(weakSelf.view);
//        make.bottom.mas_equalTo(weakSelf.view).mas_offset(49);
//    }];
    
    self.originalFrame = self.imageView.frame;
}

#pragma mark --getter & setter 

-(UIImageView *) imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc]  initWithFrame: self.view.bounds];
        _imageView.contentMode = UIViewContentModeScaleAspectFit;
        _imageView.userInteractionEnabled = YES;
        _imageView.backgroundColor = [UIColor redColor];
        
//        UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget: self action: @selector(didPinch:)];
//        [_imageView addGestureRecognizer: pinch];
        
        UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGestureDetected:)];
        [pinchGestureRecognizer setDelegate: self];
        [_imageView addGestureRecognizer:pinchGestureRecognizer];
        
        UIRotationGestureRecognizer *rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGestureDetected:)];
        [rotationGestureRecognizer setDelegate: self];
        [_imageView addGestureRecognizer:rotationGestureRecognizer];
        
        UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureDetected:)];
        [panGestureRecognizer setDelegate: self];
        [_imageView addGestureRecognizer:panGestureRecognizer];
    }
    
    return _imageView;
}

-(UIImagePickerController *)pickerVC {
    if (!_pickerVC) {
        _pickerVC = [[UIImagePickerController alloc] init];
        _pickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _pickerVC.delegate = self;
    }
    
    return _pickerVC;
}


-(void)didPinch:(UIPinchGestureRecognizer *)pinch {
    //当手指离开屏幕时,将lastscale设置为1.0
//    if(pinch.state == UIGestureRecognizerStateEnded) {
//        self.lastScale = 1.0;
//        return;
//    }
//    
//    CGFloat scale = 1.0 - (self.lastScale  - pinch.scale);
//    CGAffineTransform currentTransform = pinch.view.transform;
//    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
//    [pinch.view setTransform: newTransform];
//    self.lastScale  = pinch.scale;
    
    if (pinch.state == UIGestureRecognizerStateBegan || pinch.state == UIGestureRecognizerStateChanged) {
        CGFloat scale = [pinch scale];
        [pinch.view setTransform:CGAffineTransformScale(pinch.view.transform, scale, scale)];
        [pinch setScale:1.0];
    }
    
}

#pragma mark --UIImagePickerControllerDelegate

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = [info objectForKey: UIImagePickerControllerOriginalImage];
    NSLog(@"image.size:(%f, %f), screen(%f, %f)", image.size.width, image.size.height, self.view.frame.size.width, self.view.frame.size.height);
    CGFloat width = self.view.frame.size.width;
    CGFloat height = image.size.height * width / image.size.width;
    self.imageView.frame = CGRectMake(0, 0, width, height);
    self.imageView.center = self.view.center;
    self.imageView.image = image;
    
    [picker dismissViewControllerAnimated: YES completion: nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated: YES completion: nil];
}



#pragma mark -- UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)pinchGestureDetected:(UIPinchGestureRecognizer *)recognizer
{
    UIGestureRecognizerState state = [recognizer state];
    
    if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
    {
        CGFloat scale = [recognizer scale];
        if (recognizer.view.frame.size.width * scale < self.view.frame.size.width / 3.0
            || recognizer.view.frame.size.height * scale < self.view.frame.size.height / 3.0) {
            scale = 1.0;
        }
        
        [recognizer.view setTransform:CGAffineTransformScale(recognizer.view.transform, scale, scale)];
        [recognizer setScale: 1.0];
    }
    
    CGFloat s = self.imageView.image.size.height / self.imageView.image.size.width;
    CGRect frame2 = self.imageView.frame;
    CGFloat width = frame2.size.width;
    CGFloat height = self.imageView.image.size.height * width / self.imageView.image.size.width;
    frame2.size.width = width;
    frame2.size.height = height;
    self.imageView.frame = frame2;
    
    NSLog(@"image.scale = %f", self.imageView.image.scale);
    if (state == UIGestureRecognizerStateEnded) {
        if (self.imageView.frame.size.width < self.view.frame.size.width
            || self.imageView.frame.size.height < self.view.frame.size.height) {
            CGRect frame = self.imageView.frame;
            frame.origin.x = self.view.center.x - frame.size.width / 2.0;
            frame.origin.y = self.view.center.y - frame.size.height / 2.0;
            self.imageView.frame = frame;
        }
    }
}

- (void)panGestureDetected:(UIPanGestureRecognizer *)recognizer
{
    UIGestureRecognizerState state = [recognizer state];
    
    if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
    {
        CGPoint translation = [recognizer translationInView:recognizer.view];
        CGRect frame = recognizer.view.frame;
        
        if (CGRectGetWidth(frame) < CGRectGetWidth(self.view.frame)) {
            if (CGRectGetMaxX(frame) + translation.x > CGRectGetWidth(self.view.frame)
                || CGRectGetMinX(frame) + translation.x < 0) {
                translation.x = 0;
            }
        }
        else {
            if (CGRectGetMaxX(frame) + translation.x < CGRectGetWidth(self.view.frame)
                || CGRectGetMinX(frame) + translation.x > 0) {
                translation.x = 0;
            }
        }
        
        if (CGRectGetHeight(frame) < CGRectGetHeight(self.view.frame)) {
            if ((CGRectGetMaxY(frame)+translation.y > CGRectGetHeight(self.view.frame))
                || (CGRectGetMinY(frame) + translation.y) < 0) {
                translation.y = 0;
            }
        }
        else {
            if ((CGRectGetMaxY(frame)+translation.y < CGRectGetHeight(self.view.frame))
                || (CGRectGetMinY(frame) + translation.y) > 0) {
                translation.y = 0;
            }
        }
        
        CGAffineTransform transform = CGAffineTransformTranslate(recognizer.view.transform, translation.x, translation.y);
        [recognizer.view setTransform: transform];
        [recognizer setTranslation:CGPointZero inView:recognizer.view];
    }
}

- (void)rotationGestureDetected:(UIRotationGestureRecognizer *)recognizer
{
    UIGestureRecognizerState state = [recognizer state];
    
    if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
    {
        CGFloat rotation = [recognizer rotation];
        [recognizer.view setTransform:CGAffineTransformRotate(recognizer.view.transform, rotation)];
        [recognizer setRotation:0];
    }
}

@end
